/*
 * @Author: 糊涂的老知青
 * @Date: 2022-07-30
 * @Version: 1.0.0
 * @Description:
 */
package infra_domainservice

import (
	"lzq-admin/base/domainservice"
	infra_model "lzq-admin/internal/infrastructure/model"
	"lzq-admin/pkg/orm"
	"lzq-admin/pkg/utility"
	"sync"

	"github.com/gin-gonic/gin"

	"github.com/pkg/errors"
)

/**
 * @Author  糊涂的老知青
 * @Date    2021/12/1
 * @Version 1.0.0
 */

// AuthModuleDomainService 服务模块领域服务
type AuthModuleDomainService struct {
	domainservice.BaseDomainService
	wg sync.WaitGroup
}

func NewDSAuthModule(c *gin.Context) *AuthModuleDomainService {
	return &AuthModuleDomainService{
		domainservice.BaseDomainService{
			GinCtx: c,
		},
		sync.WaitGroup{},
	}
}

func (s *AuthModuleDomainService) Insert(modelDto infra_model.CreateAuthModuleDto) (result infra_model.AuthModule, err error) {
	var entity infra_model.AuthModule
	var exist bool
	exist, err = orm.NewLzqOrm(s.GinCtx).QSession(false).Where("code=?", modelDto.Code).Exist(&infra_model.AuthModule{})
	if err != nil {
		return entity, err
	}
	if exist {
		return entity, errors.New("模块编码：" + modelDto.Code + " 已存在，请更换模块编码")
	}
	entity = infra_model.AuthModule{
		AuthModuleBase: infra_model.AuthModuleBase{
			Code: modelDto.Code,
			Name: modelDto.Name,
			Rank: modelDto.Rank,
		},
	}
	entity.ID = utility.UuidCreate()
	_, err = orm.NewLzqOrm(s.GinCtx).ISession().Insert(&entity)
	return entity, err
}

func (s *AuthModuleDomainService) Get(id, code string) (infra_model.AuthModuleDto, error) {
	var has bool = false
	var err error
	var dto infra_model.AuthModuleDto
	db := orm.NewLzqOrm(s.GinCtx).QSession(false)
	if len(id) > 0 {
		has, err = db.ID(id).Get(&dto)
	} else if len(code) > 0 {
		has, err = db.Where("Code=?", code).Get(dto)
	}
	if err != nil {
		return dto, err
	}
	if has {
		return dto, nil
	} else {
		return dto, errors.New("模块ID/模块编码不存在或已删除")
	}
}
